<?php
/**
 * 海带供应商SDK
 * @author chenshubo
 */
namespace App\Service\VendorClient\ShophdApi;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use App\Model\CommodityModel\WarehouseInfo;
use Hyperf\Utils\WaitGroup;
use App\Model\PssModel\ServiceConfig;
use App\Model\PssModel\OrderSupplier;
use function GuzzleHttp\json_encode;

class ShophdApiClient
{
    private $account  = 'Shophd';
    protected $config;
    protected $RouteMap = [
        'getAccessToken'        => '/ssoapi/v2/login/login',
        'queryGoodsList'        => '/api/v2/goods/searchingGoods',
        'queryGoodsDetail'      => '/api/v2/goods/getGoodsInfo',
        'queyrGoodsPrice'       => '/api/v2/goods/getNewGoodsPrice',
        'createOrder'           => '/api/v2/order/createOrders',
        'orderAfterSale'        => '/api/v2/order/apply',
        'orderCancel'           => '/api/v2/order/orderCancel',
        'orderPay'              => '/api/v2/finance/toPayForBalanceWithoutCode',
        'orderDeclare'          => '/api/v2/order/reDeclare',
    ];
    //海带地区redis key
    const REGION_CACHE_PREFIX = 'hd_region';

    public function __construct($apiBody = []){
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
/**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo1");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];

        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        
        if(!isset($apply_extends["isPayOrder"])){
            //获取下单商品信息
            $goodsSnsList       = [];
            $numsList           = [];
            $productNumsList    = [];
            foreach ($params['orderGoods'] as $item )
            {
                $goodsSnsList[]     = $item['supplier_skucode'];
                $numsList[]         = $item['quantity'];
                $productNumsList[]  = $item['spec_num'];
                
            }
            //拼接城字符串
            $goodsSns       = !empty($goodsSnsList)?implode(",",$goodsSnsList) : '';
            $nums           = !empty($numsList)?implode(",",$numsList) : '';
            $productNums    = !empty($productNumsList)?implode(",",$productNumsList) : '';
            
            //支付拓展信息
            $apply_extends      = @json_decode($orderInfo['apply_extends'],true);
            $apply_extends      = empty($apply_extends) ? $order : $apply_extends;
            
            //支付流水号
    
            $pay_sn         = $order['paySerial']??$orderInfo['pay_sn'];
            
            //获取上游供应商支付方式路由
            $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
            $payCommanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
            
            $pay_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_PAY, $payCommanyCode);
            if (empty($pay_value)) {
                return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$payCommanyCode}】未映射，请联系管理员处理");
            }
            
            //创建订单数据
            $data = [
                'area'              => $this->config['regionId'],
                'accountId'         => $this->config['accountId'],
                'goodsSns'          => $goodsSns,
                'nums'              => $nums,
                'name'              => $orderInfo["receive_name"],
                'productNums'       => $productNums,
                'mobile'            => $orderInfo['recveive_phone'],
                'appkey'            => $this->config["appkey"],
                'address'           => $orderInfo['province'].$orderInfo['city'].$orderInfo['district'].$orderInfo['receive_address'],
                'memberId'          => $this->config["memberId"],
                'identification'    => $orderInfo['buyer_idcard'],
                'thirdBuyAmount'    => (float)$orderInfo["real_total_money"],
                'thirdOrderNo'      => $orderInfo['supplier_dsn'],
                'paymentId'         => $pay_value,
                'customOrder'       => $orderInfo['supplier_dsn'],
                'remarks'           => !empty($orderInfo['order_remark']) ? $orderInfo['order_remark'] : "尽快发货",
                'eceName'           => $this->config['eceName'],
                'eceRecordNumber'   => $this->config['eceRecordNumber'],
                'payOrderNo'        => $orderInfo['supplier_dsn'],
                'payTradeNo'        => $pay_sn,
            ];
            
            $requestParam = [
                'method'    => 'createOrder',
                'data'      => $this->getSignParam($data),
            ];
            $res  = $this->execute($requestParam);
            if($res["code"] != Normal::SUC){
                return $res;
            }
            
        }

        if(isset($apply_extends["isPayOrder"]) && $apply_extends["isPayOrder"] == 1){
            return Normal::returnCode(Normal::SUC,"推单成功");
        }
        
        //如果是海外直邮商品，且没有调用报关信息接口的或者失败的，则需要调用报关信息接口
        if($params['orderGoods'][0]["goods_type"] == 2){
            if(!isset($apply_extends["isDeclareOrder"]) or  $apply_extends["isDeclareOrder"] == 0){
                $orderDeclareRes = $this->orderDeclare($params);
                $apply_extends["isDeclareOrder"]    = $orderDeclareRes["code"] == Normal::SUC ? 1 : 0;
                $apply_extends["isDeclareOrderMsg"] = $orderDeclareRes["msg"];
            }
        }
        $orderPayRes = $this->orderPay($orderInfo['supplier_dsn']);
        $apply_extends["isPayOrder"]    = $orderPayRes["code"] == Normal::SUC ? 1 : 0;
        $apply_extends["isPayOrderMsg"] = $orderPayRes["msg"];
        
        //将推单结果存入$apply_extends
        $new_apply_extends = json_encode($apply_extends,JSON_UNESCAPED_UNICODE);
        OrderSupplier::instance()->where("supplier_dsn",$orderInfo['supplier_dsn'])->update(["apply_extends"=>$new_apply_extends]);
        return $orderPayRes;
    }

    /**
     * 取消订单
     * @param array $params
     * @return mixed
     */
    public function cancelOrder($params = []){
        return Normal::returnCode(Normal::SUC,"处理完成");
    }
    
    /**
     * 余额扣款
     * @param array $params
     * @return mixed
     */
    public function orderPay($orderSn){
        //余额扣款单数据
        $data = [
            'memberId'          => $this->config["memberId"],
            'orderSns'          => $orderSn,
        ];
        $requestParam = [
            'method'    => 'orderPay',
            'data'      => $this->getSignParam($data),
        ];
        $res  = $this->execute($requestParam);
        return $res;
    }
    /**
     * 订单申报
     * @param array $params
     * @return mixed
     */
    public function orderDeclare($params = []){
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];

        //支付拓展信息
        $apply_extends      = @json_decode($orderInfo['apply_extends'],true);
        $apply_extends      = empty($apply_extends) ? $order : $apply_extends;
        //判断是否传了身份证正反面
        if(!isset($apply_extends["idCardBackImage"]) or !isset($apply_extends["idCardBackImage"])){
            return Normal::returnCode(Normal::FAIL,"身份证正反面不能为空");
        }
        //查询区域id
        $areaInfo = $this->getHdOrderRegion($orderInfo['province'],$orderInfo['city'],$orderInfo['district']);
        if($areaInfo["code"] != Normal::SUC){
            return $areaInfo;
        }
        $area = $areaInfo["data"]["district"];
        //申报订单数据
        $data = [
            'orderSn'           => $orderInfo['supplier_dsn'],
            'memberId'          => $this->config["memberId"],
            'address'           => $orderInfo['province'].$orderInfo['city'].$orderInfo['district'].$orderInfo['receive_address'],
            'identification'    => $orderInfo['buyer_idcard'],
            'mobile'            => $orderInfo['buyer_phone'],
            'area'              => $area,
            'name'              => $orderInfo['buyer_realname'],
            'emblumside'        => $apply_extends["idCardBackImage"],
            'photoside'         => $apply_extends["idCardFrontImage"],
        ];
        $requestParam = [
            'method'    => 'orderDeclare',
            'data'      => $this->getSignParam($data),
        ];
        $res  = $this->execute($requestParam);
        return $res;
    }
    /**
     * 订单售后
     * @param array $params
     * @return mixed
     */
    public function orderAfterSale($params = []){
        $supplierOrder = $params['supplierOrder'];
        $order         = $params['order'];
        $orderGoods    = $params['orderGoods'];

        //下单支付的时候支付信息
        $apply_extends  = @json_decode($supplierOrder['apply_extends'],true);
        
        //判断海带是否调用余额扣款成功，调用了返回成功走人，否则调取消接口
        if(!isset($apply_extends["isPayOrder"]) or $apply_extends["isPayOrder"] == 0){
            //取消订单数据
            $data = [
                'orderSns'   => $supplierOrder['supplier_dsn'],
                'memberId'   => $this->config["memberId"],
                'reason'     => $order['exceptReason']
            ];
            $requestParam = [
                'method'    => 'orderCancel',
                'data'      => $this->getSignParam($data),
            ];
            $res  = $this->execute($requestParam);
            return $res;
            
        }
        return Normal::returnCode(Normal::SUC,"处理完成");
    }

    /**
     * 查询商品信息
     */
    public function queryGoodsList($param)
    {
        //获取token
        $access_token = $this->getAccessToken($param["supplierID"]);
        if($access_token["code"] != Normal::SUC){
            return $access_token;
        }
        $token = $access_token["data"];
        $this->token = $token;
        
        //获取商品指定城市区域信息
        if(isset($this->config["cityId"])){
            $cityId = $this->config["cityId"];
        }else{ 
            return Normal::returnCode(Normal::FAIL,"请指定cityId");
        }
        if(isset($this->config["regionId"])){
            $regionId = $this->config["regionId"];
        }else{
            return Normal::returnCode(Normal::FAIL,"请指定regionIdId");
        }
        
        //获取商品列表
        $goodsWhere = [
            'memberId'  => $this->config["memberId"],
            'appkey'    => $this->config["appkey"],
            'pageSize'  => $param['limit']  ?? 50,
            'pageNum'   => $param['page']  ?? 1,
            'tradeType' => $this->config["tradeType"],//1101一般贸易，2202保税，1303海外直邮
        ];
        $requestParam = [
            'method'    => 'queryGoodsList',
            'data'      => $this->getSignParam($goodsWhere),
        ];
        $res  = $this->execute($requestParam);
        if($res["code"] != Normal::SUC or empty($res["data"]["result"])){
            return $res;
        }

        //获取商品详情和商品价格
        $result_goods = $res["data"]["result"];
        $details = [];
        foreach ($result_goods as $sku) 
        {
            //预定义参数
            $sku["goodsDetailImages"] =  [];
            $sku["barCode"]           =  "";
            $sku["intro"]             =  "";
            $sku["unit"]              =  "";
            $sku["generalProductLifeList"] =  [];
            
            //查询商品详情
            $detailsWhere = [
                'memberId'  => $this->config["memberId"],
                'goodsId'   => $sku["goodsId"],
                'appkey'    => $this->config["appkey"],
            ];
            $requestParam = [ 
                'method'    => 'queryGoodsDetail',
                'data'      => $this->getSignParam($detailsWhere),
            ];
            $detailsResponse = $this->execute($requestParam);
            if ( $detailsResponse['code']== Normal::SUC && isset($detailsResponse['data']) && $detailsResponse['data'] )
            {
                $sku["goodsDetailImages"] =  $detailsResponse['data']["goodsDetailImages"];
                $sku["barCode"]           =  $detailsResponse['data']["barCode"];
                $sku["intro"]             =  $detailsResponse['data']["intro"];
                $sku["unit"]              =  $detailsResponse['data']["unit"];
            }
    
            //查询商品价格
            $priceWhere = [
                'memberId'  => $this->config["memberId"],
                'accountId' => $this->config["accountId"],
                'cityId'    => $this->config["cityId"],
                'regionId'  => $this->config["regionId"],
                'goodsId'   => $sku["goodsId"],
            ];
            $requestParam = [
                'method'    => 'queyrGoodsPrice',
                'data'      => $this->getSignParam($priceWhere),
            ];
            $priceRresponse = $this->execute($requestParam);
            if ( $priceRresponse['code']== Normal::SUC && isset($priceRresponse['data']) && $priceRresponse['data'] )
            {
                $sku["generalProductLifeList"] =  $priceRresponse['data']["generalProductLifeList"];
            }
            $details[] = $sku;
        }
        
        if(empty($details)) {
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'data'      => [],
                'has_next'  => false
            ]);
        }
        
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'data'      => $details,
            'has_next'  => true
        ]);
        
    }
    
//     /**
//      * 查询商品信息
//      */
//     public function queryGoodsList($param)
//     {
//         //获取token
//         $access_token = $this->getAccessToken($param["supplierID"]);
//         if($access_token["code"] != Normal::SUC){
//             return $access_token;
//         }
//         $token = $access_token["data"];
//         $this->token = $token;
    
//         //获取商品指定城市区域信息
//         if(isset($this->config["cityId"])){
//             $cityId = $this->config["cityId"];
//         }else{
//             return Normal::returnCode(Normal::FAIL,"请指定cityId");
//         }
//         if(isset($this->config["regionId"])){
//             $regionId = $this->config["regionId"];
//         }else{
//             return Normal::returnCode(Normal::FAIL,"请指定regionIdId");
//         }
    
//         //获取商品列表
//         $goodsWhere = [
//             'memberId'  => $this->config["memberId"],
//             'appkey'    => $this->config["appkey"],
//             'pageSize'  => $param['limit']  ?? 50,
//             'pageNum'   => $param['page']  ?? 1,
//             'tradeType' => $this->config["tradeType"],//1101一般贸易，2202保税，1303海外直邮
//         ];
//         $requestParam = [
//             'method'    => 'queryGoodsList',
//             'data'      => $this->getSignParam($goodsWhere),
//         ];
//         $res  = $this->execute($requestParam);
//         if($res["code"] != Normal::SUC){
//             return $res;
//         }
    
//         //获取商品详情和商品价格
//         $result_goods = $res["data"]["result"];
//         $details = [];
//         $selfSellTypeSkip = [];
//         $chunkList = array_chunk($result_goods,$this->config['price_limit_count']);
//         foreach ($chunkList as $result_query_goods)
//         {
//             $wg = new WaitGroup();
//             $count = count($result_query_goods);
//             $wg->add($count);
//             foreach ($result_query_goods as $sku)
//             {
//                 co(function () use ($wg,$sku, & $details, & $selfSellTypeSkip)
//                 {
    
//                     //预定义参数
//                     $sku["goodsDetailImages"] =  [];
//                     $sku["barCode"]           =  "";
//                     $sku["intro"]             =  "";
//                     $sku["unit"]              =  "";
//                     $sku["generalProductLifeList"] =  [];
    
//                     //查询商品详情
//                     $detailsWhere = [
//                         'memberId'  => $this->config["memberId"],
//                         'goodsId'   => $sku["goodsId"],
//                         'appkey'    => $this->config["appkey"],
//                     ];
//                     $requestParam = [
//                         'method'    => 'queryGoodsDetail',
//                         'data'      => $this->getSignParam($detailsWhere),
//                     ];
//                     $detailsResponse = $this->execute($requestParam);
//                     if ( $detailsResponse['code']== Normal::SUC && isset($detailsResponse['data']) && $detailsResponse['data'] )
//                     {
//                         $sku["goodsDetailImages"] =  $detailsResponse['data']["goodsDetailImages"];
//                         $sku["barCode"]           =  $detailsResponse['data']["barCode"];
//                         $sku["intro"]             =  $detailsResponse['data']["intro"];
//                         $sku["unit"]              =  $detailsResponse['data']["unit"];
//                     }
    
//                     //查询商品价格
//                     $priceWhere = [
//                         'memberId'  => $this->config["memberId"],
//                         'accountId' => $this->config["accountId"],
//                         'cityId'    => $this->config["cityId"],
//                         'regionId'  => $this->config["regionId"],
//                         'goodsId'   => $sku["goodsId"],
//                     ];
//                     $requestParam = [
//                         'method'    => 'queyrGoodsPrice',
//                         'data'      => $this->getSignParam($priceWhere),
//                     ];
//                     $priceRresponse = $this->execute($requestParam);
//                     if ( $priceRresponse['code']== Normal::SUC && isset($priceRresponse['data']) && $priceRresponse['data'] )
//                     {
//                         $sku["generalProductLifeList"] =  $priceRresponse['data']["generalProductLifeList"];
//                     }
//                     $details[] = $sku;
//                     $wg->done();
//                 });
//             }
//             $wg->wait();
//         }
    
//         if(empty($details)) {
//             return Normal::returnCode(Normal::SUC,"获取成功",[
//                 'data'      => [],
//                 'has_next'  => false
//             ]);
//         }
    
//         return Normal::returnCode(Normal::SUC,"获取成功",[
//             'data'      => $details,
//             'has_next'  => true
//         ]);
    
//     }
    
    /**
     * 查询token值
     * @param array $param
     */
    public function getAccessToken( $supplierID )
    {
        $redis = redis();
        $cache_key = $this->account."_AccessToken";
        $AccessToken = $redis->get($cache_key);
        if(empty($AccessToken)){
            $data = [
                'username'      => $this->config["username"],
                'password'      => md5($this->config["password"]),
                'appkey'        => $this->config["appkey"],
            ];
            $requestParam = [
                'method'    => 'getAccessToken',
                'data'      => $this->getSignParam($data)
            ];
            $res =  $this->execute($requestParam);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }
            $TokenInfo = $res["data"];
            //将memberId，accountId存入仓库配置中
            $this->config["memberId"] = $TokenInfo["memberId"];
            $this->config["accountId"] = $TokenInfo["accountId"];
            $JsonBody = json_encode($this->config,JSON_UNESCAPED_UNICODE);
            $AccessToken = $TokenInfo["token"];
            WarehouseInfo::instance()->where("SupplierID",$supplierID)->update(["JsonBody"=>$JsonBody]);
            $redis->set($cache_key,$AccessToken,60*60*23*10);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$AccessToken);
    }

    /*
     * 获取海带下单地址
     */
    protected function getHdOrderRegion($province, $city,$district)
    {
        $houniaoProvinceList = $this->getAllRegions();
        if (empty($houniaoProvinceList)) {
            return Normal::returnCode(Normal::FAIL, "获取省份信息失败，请重试！");
        }
        //组装省市区地址
        $param['region'] = [
            'province' => $province,
            'city'     => $city,
            'district' => $district,
        ];
        //获取province code
        if (isset($houniaoProvinceList[$province])) {
            $provinceCode = $houniaoProvinceList[$province];
        } else if (isset($houniaoProvinceList[$province . "市"])) {
            $provinceCode = $houniaoProvinceList[$province . "市"];
        } else if (isset($houniaoProvinceList[$province . "省"])) {
            $provinceCode = $houniaoProvinceList[$province . "省"];
        } else if (isset($houniaoProvinceList[$province . "自治区"])) {
            $provinceCode = $houniaoProvinceList[$province . "自治区"];
        } else {
            return Normal::returnCode(Normal::FAIL, "省份不正确，请核对！");
        }

        $redis = redis();
        //获取city code
        $cityList = $redis->hGet(self::REGION_CACHE_PREFIX,(string)$provinceCode);
        if (empty($cityList)) {
            return Normal::returnCode(Normal::FAIL, "市信息获取失败-1");
        }
        $cityList = json_decode($cityList, true);
        $cityMap  = array_column($cityList, 'regionId', 'regionName');
    
        if (isset($cityMap[$city])) {
            $cityCode = $cityMap[$city];
        } else if (isset($cityMap[$city . '市'])) {
            $cityCode = $cityMap[$city . '市'];
        } else {
            return Normal::returnCode(Normal::FAIL, "市信息获取失败-2");
        }
        //获取地区
        $districtMap = array_column($cityList[$cityCode]['children'], 'regionId', 'regionName');
        //获取district code
        if (isset($districtMap[$district])) {
            $districtCode = $districtMap[$district];
            //如果是区
        } else if (isset($districtMap[$district . "区"])) {
            $districtCode = $districtMap[$district . "区"];
            //如果是县
        } else if (isset($districtMap[$district . "县"])) {
            $districtCode = $districtMap[$district . "县"];
            //如果是县升级为区
        } else if (strpos($district, "县") !== false && isset($districtMap[str_replace("县", "", $district) . "区"])) {
            $districtCode = $districtMap[str_replace("县", "", $district) . "区"];
        } else {
            return Normal::returnCode(Normal::FAIL, "地区不正确，请核对！");
        }
        $param['province'] = $provinceCode;
        $param['city']     = $cityCode;
        $param['district'] = $districtCode;
        return Normal::returnCode(Normal::SUC, "查询成功", $param);
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] ){
        
        $method = $param["method"];
        $url    = $this->config["baseurl"].$this->RouteMap[$method];
        $parameter = [
            [
                'tag'    => 'shophd_' . $method,
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $param['data'],
                'method' => 'post',
                'format' => 'x-www-form-urlencoded',
                'header' => []
            ]
        ];
        if( in_array($method,['queryGoodsList','getAccessToken','queryGoodsDetail','queyrGoodsPrice']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask   = current($resTask);
        $response  = $resTask['response']['result'];
        $result    = @json_decode($response, true);
        if (isset($result['result']) && $result['result'] == 1) {
            return Normal::returnCode(Normal::SUC, "OK",$result["data"]);
        }
        $message = $result['message'] ?? '操作失败';
        return Normal::returnCode(Normal::FAIL, $message);
        
    }
  
    /**
     * 获取地区信息
     */
    private function getAllRegions(){

        $redis = redis();
        $list  = $redis->hGet(self::REGION_CACHE_PREFIX, '0');
        if (!empty($list)) {
            return json_decode($list, true);
        }
        $parameter = [
            [
                'tag'    => 'shophd_queryRegions',
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $this->config['API_REGION'],
                'data'   => [],
                'method' => 'get',
                'format' => 'json',
                'header' => [
                    "Content-Type: application/json",
                    "Accept:application/json"
                ]
            ]
        ];
        $resTask   = TaskWorker::instance()->addTask($parameter,"handleDiableTask");
        $resTask   = current($resTask);
        $response  = $resTask['response']['result'];
        $regions   = @json_decode($response, true);
        if (empty($regions)) {
            return false;
        }
        $firstAreaInfo = array_column($regions, 'regionId', 'regionName');
        $redis->hSet(self::REGION_CACHE_PREFIX, '0', json_encode($firstAreaInfo, JSON_UNESCAPED_UNICODE));
        //分散省份数据
        foreach ($regions as $province_code => & $data) {
            //处理市为市辖区
            if (in_array($data['regionName'], ['北京市', '天津市', '上海市', '重庆市'])) {
                $areaInfo                                              = current($data['children']);
                $data['children'][$areaInfo['regionId']]['regionName'] = '市辖区';
            }
            $province_data = $data['children'] ? json_encode($data['children'],JSON_UNESCAPED_UNICODE) : [];
            $redis->hSet(self::REGION_CACHE_PREFIX,(string)$province_code,$province_data);
        }
        return $firstAreaInfo;
    }
    /**
     * 加签 参数
     */
    private function getSignParam($param){
        //合并公共参数
        $param     = array_merge($param, $this->getCommonParam());
        $signParam = self::argSort($param);
        //url 加码
        $signParam        = self::getUrlEncode($signParam);
        $createLinkstring = self::createLinkstring($signParam);
        //处理*号不转义的问题
        $createLinkstring = str_replace("%2A", "*", $createLinkstring);
        $second           = $this->config["appSecret"] . $createLinkstring . $this->config["appSecret"];
        $param['topSign'] = strtoupper(sha1($second));
        return $param;
    }

    /**
     * 获取签名公共参数
     */
    private function getCommonParam() {
        return [
//             'username'  => $this->config['username'],
//             'password'  => md5($this->config['password']),
            'appkey'    => $this->config["appkey"],
            'timestamp' => self::get_total_millisecond(),
        ];
    }

    /*
     *返回字符串的毫秒数时间戳 13位
     */
    private static function get_total_millisecond() {
        $temptime  = explode(" ", microtime());
        $time      = $temptime [1];
        $temptime  = $temptime[0] * 1000;
        $newNumber = substr(strval($temptime + 1000), 1, 3);
        return $time . $newNumber;
    }

    /**
     * 对数组排序
     */
    private static function argSort($para) {
        ksort($para);
        reset($para);
        return $para;
    }

    /**
     * 参数url 加码
     * @param array $param
     */
    private static function getUrlEncode( $param = [] ) {
        foreach ($param as & $val ) {
            $val = urlencode($val);
        }
        return $param;
    }

    /**
     * 把数组所有元素，按照"参数=参数值"的模式用"&"字符拼接成字符串
     * @param $para 需要拼接的数组
     * @return 拼接完成以后的字符串
     */
    private static function createLinkstring($para) {
        $arg = [];
        foreach ($para as $key => $val ) {
            $arg[] = $key."=".$val;
        }

        $arg = implode("&", $arg);
       // if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
        return $arg;
    }
}